package cn.zy.basic.controller;

import cn.zy.basic.util.AjaxResult;
import cn.zy.basic.util.FastDfsUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传 - 需要【请求方式：post】
 * 下载 - 不需要
 * 删除 - 需要【请求方式：delete】
 * 修改 - 不需要 = 先删除再上传
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    /**
     * 文件上传接口
     * @param file
     * @return
     */
    @PostMapping
    public AjaxResult uploadFile(@RequestPart MultipartFile file){//file必须和前端属性对应
        try {
            String oName = file.getOriginalFilename();//xxx.jpg
            String exeName = oName.substring(oName.lastIndexOf(".") + 1);//jpg - 含头不含尾,所以+1
//调工具类
            String fileName = FastDfsUtils.upload(file.getBytes(), exeName);
            return AjaxResult.me().setObj(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"上传失败!");
        }
    }

    /**
     * 删除接口
     * @return
     * delete http://localhost:8080/fastDfs/group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
     * 后端接收：@PathV("/{a}/{b}/{c}/{d}")
     * delete http://localhost:8080/fastDfs?path=/group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam("path") String path){//file必须和前端属性对应
        try {
            //path = /group1/M00/03/8C/CgAIC2PeKiOAGGJNAAAm8GA0XBk948.jpg 想办法获取工具类所需参数
            path = path.substring(1);//去掉path的第一个/
            String groupName = path.substring(0, path.indexOf("/"));//组名groupName - group1
            String fileName = path.substring(path.indexOf("/") + 1);
            FastDfsUtils.delete(groupName,fileName);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败!");
        }
    }
}
